'use strict';
let gulp = require('gulp');
let babel = require('gulp-babel');
//let fs=require("fs");
let plumber = require('gulp-plumber');
let path = require('path');
let clean = require('gulp-clean');
//let less=require("gulp-less");
//let destChmod=require("./gulp-dest-chmod");
//let webpack=require("gulp-webpack");
//let named = require("vinyl-named");
let {
    ZPack
} = require('../z-pack');
let changed = require('gulp-changed');
let ejs = require('ejs');

let babelOpt = {
    'presets': [
        /* "latest", */
        'react',
        /* "stage-0"  */
    ],
    'plugins': [
        'babel-plugin-transform-es2015-modules-commonjs',
        'babel-plugin-transform-export-extensions',
        'babel-plugin-transform-class-properties',
        'transform-decorators-legacy',
        'babel-plugin-transform-object-rest-spread',
        ['import', {
            'libraryName': 'antd',
            'style': true
        }]
    ],
    'compact': 'false'
};

gulp.task('default', function() {
    return gulp.src(['view/**/*', '!view/**/*.ejs', '!view/**/*.d.ts'])
        .pipe(changed('build'))
        .pipe(plumber())
        .pipe(ZPack({
            rootPath: path.join(__dirname, 'view'),
            babel: babelOpt,
            pageTemplate: [{
                match: /^\/pages\/(.*?)(\.[tj]sx?)*$/,
                template: path.join(__dirname, 'view', 'template.html'),
                path: '/$1.html',
                render: async (contents, data) => {
                    return ejs.render(contents, data);
                }
            }],
            external: {
                'react': 'React',
                'react-dom': 'ReactDOM'
            },
            preload: ['/node_modules/all.bundle.js']
        }))
        .pipe(plumber())
        .pipe(gulp.dest('build'));
});

gulp.task('clean', function() {
    return gulp.src('build').pipe(clean());
});

gulp.task('modules', function() {
    return gulp.src(['view/**/*', '!view/**/*.d.ts'])
        .pipe(changed('build'))
        .pipe(plumber())
        .pipe(ZPack({
            rootPath: path.join(__dirname, 'view'),
            babel: babelOpt,
            assembly: 'modulesAllInOne',
            external: {
                'react': 'React',
                'react-dom': 'ReactDOM'
            },
            less: {
                javascriptEnabled: true
            }
        }))
        .pipe(plumber())
        .pipe(gulp.dest('build'));
});

gulp.task('watch', ['default'], function() {
    gulp.watch(['view/**/*', '!view/**/*.d.ts'], ['default']);
});
